package com.njuse_czf.kg.web.service.impl.handler;

import com.njuse_czf.kg.web.request.GraphQuery;
import com.njuse_czf.kg.web.service.KGGraphService;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.stream.Collectors;

public class AdvantageHandler extends AbstractQuestionHandler{

    @Override
    public void handleQuestion(QuestionCtx questionCtx, String question, KGGraphService kgGraphService) {
        String regix = "[Ww]hat(?:'s|\\s+is)\\s+the\\s+advantage\\s+of\\s+([^?]+)\\s*\\??";


        Pattern pattern = Pattern.compile(regix, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(question);

        if (matcher.find()) {
            //提取匹配到的名词
            String name = matcher.group(1);
            List<String> nodes = getAllObject(name);

            for (String nodeName : nodes) {
                //构造Query
                GraphQuery query = new GraphQuery();
                query.setDomain(questionCtx.getDomain());
                query.setMatchType(1);
                String subName = fuzzyMatching(nodeName.toLowerCase());
                query.setNodeName(subName);
                query.setRelation(new String[]{"advantage"});

                List<HashMap> res = (List<HashMap>) kgGraphService.queryGraphResult(query).get("node");

                //提取出实体的优点
                List<String> nodeNames = res.stream()
                        .map(map -> (String) map.get("name"))
                        .filter(s -> !s.equals(nodeName))
                        .collect(Collectors.toList());

                String currentAnswer = nodeNames.stream()
                        .map(s -> s.endsWith(".") ? s.substring(0, s.length() - 1) : s)
                        .collect(Collectors.joining(","));

                if (!currentAnswer.isEmpty()) {
                    currentAnswer = "The advantage of " + nodeName + " is " + currentAnswer + ".\n";
                    questionCtx.addAnswer(currentAnswer);
                    //删除已经匹配的部分
                    question = matcher.replaceFirst("");
                }
                else{
                    String node = getClosestNode(subName);
                    String sorryAnswer = "Sorry, I can't find entity named \"" + nodeName + "\". Are you actually looking for \"" + node + "\"?\n";
                    questionCtx.addAnswer(sorryAnswer);
                    question = matcher.replaceFirst("");
                }
            }
        }

        this.getNextHandler().handleQuestion(questionCtx, question, kgGraphService);
    }
}
